package com.kotlin.demo.tools

import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import com.kotlin.demo.constant.Constants.TRANSLATE_LIST_TAG
import com.kotlin.demo.enums.WriterType
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.NodeList
import java.io.*
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
import javax.xml.parsers.DocumentBuilderFactory

object StringsUtils {
    /**
     * 开始插入多语言
     */
    fun startInsertLanguage(
        translateKey: String,
        transMap: HashMap<String, String>,
        resPath: String,
        writerType: WriterType
    ) {
        val file = File(resPath)
        if (!file.exists()) {
            println("${resPath}不存在或无法读写")
            return
        }
        println("translateKey：${translateKey}")
        transMap.forEach { (key, value) ->
            if (TRANSLATE_LIST_TAG.any { it.shortName == key }) {
                println("翻译语言：${key}|${value}")
                val valueName = TRANSLATE_LIST_TAG.find { it.shortName == key }?.valuesName// values 多语言名称
                val resAllPath =
                    resPath + File.separator + "values-" + valueName + File.separator + "strings.xml"// 当前要插入的多语言的全路径
                println("resAllPath:${resAllPath}")
                println("valueName:${valueName}")
                val keyTag = "</resources>"
                val valueContent = "    <string name=\"${translateKey}\">$value</string>\n</resources>"
                if (key == "en") {//英语情况下多一步插入到默认语言栏
                    val resEnPath =
                        resPath + File.separator + "values" + File.separator + "strings.xml"// 当前要插入的多语言的全路径
                    if (writerType == WriterType.INSERT) {
                        writerTranslateInFile(resEnPath, keyTag, valueContent)
                    } else {
                        replaceTranslateInFile(resEnPath, translateKey, value)
                    }
                }
                if (writerType == WriterType.INSERT) {
                    writerTranslateInFile(resAllPath, keyTag, valueContent)
                } else {
                    replaceTranslateInFile(resAllPath, translateKey, value)
                }
            } else {
                println("插入语言：${key}|不存在")
            }
        }
    }

    /**
     * 写入翻译到对应的文件
     */
    private fun writerTranslateInFile(filePath: String, oldString: String, newString: String) {
        // 读取文件内容
        val file = File(filePath)
        if (!file.exists() || !file.canRead() || !file.canWrite()) {
            println("文件不存在或无法读写")
            return
        }
        var content: String
        BufferedReader(FileReader(file)).use { reader ->
            content = reader.readLines().joinToString("\n")
        }
        // 替换字符串
        val replacedContent = content.replace(oldString, newString)
        // 写入新内容到文件
        BufferedWriter(FileWriter(file)).use { writer ->
            writer.write(replacedContent)
        }
        println("${newString}字符串替换成功")
    }

    /**
     * 替换旧的翻译 value
     */
    private fun replaceTranslateInFile(filePath: String, keyTag: String, newString: String) {
        // 读取文件内容
        val file = File(filePath)
        if (!file.exists() || !file.canRead() || !file.canWrite()) {
            println("文件不存在或无法读写")
            return
        }
        var content: String
        BufferedReader(FileReader(file)).use { reader ->
            content = reader.readLines().joinToString("\n")
        }
        // 替换字符串
        val replacedContent =
            content.replace(Regex("(?<=<string name=\"${keyTag}\">).*?(?=</string>)"), newString)
        // 写入新内容到文件
        BufferedWriter(FileWriter(file)).use { writer ->
            writer.write(replacedContent)
        }
        println("${newString}字符串替换成功")
    }

    /**
     * 检测当前多语言是否存在
     */
    fun isExistTranslateKey(filePath: String, translateKey: String): Boolean {
        // 读取文件内容
        val file = File(filePath + File.separator + "values" + File.separator, "strings.xml")
        if (!file.exists() || !file.canRead() || !file.canWrite()) {
            println("文件不存在或无法读写${file.absolutePath}|${file.exists()}|${file.canRead()}|${file.canWrite()}")
            return false
        }
        var content: String
        BufferedReader(FileReader(file)).use { reader ->
            content = reader.readLines().joinToString("\n")
        }
        return content.contains("name=\"${translateKey}\"")
    }

    /**
     * 根据英文翻译获取res key
     */
    fun getTranslateKey(languageEn: String): String {
        return languageEn.trim().replace(" ", "_").replace("-", "_").replace(",", "_")
            .replace("\'", "_").replace("，", "_").replace(".", "").replace("。", "")
            .lowercase(Locale.getDefault())
    }

    /**
     * 通过key 移除对应的多语言
     */
    fun removeTranslateByKey(filePath: String, keyTag: String) {
        // 读取文件内容
        val file = File(filePath)
        if (!file.exists() || !file.canRead() || !file.canWrite()) {
            println("文件不存在或无法读写")
            return
        }

        TRANSLATE_LIST_TAG.forEach { (_, value) ->
            val valueName = value// values 多语言名称
            var resAllPath: String
            if (value == "en") {
                resAllPath =
                    filePath + File.separator + "values" + File.separator + "strings.xml"// 当前要插入的多语言的全路径
                removeTranslateByKeySingle(resAllPath, keyTag)
            }
            resAllPath =
                filePath + File.separator + "values-" + valueName + File.separator + "strings.xml"// 当前要插入的多语言的全路径
            println("resAllPath:${resAllPath}")
            println("valueName:${valueName}")
            removeTranslateByKeySingle(resAllPath, keyTag)
        }

    }

    private fun removeTranslateByKeySingle(filePath: String, keyTag: String) {
        // 读取文件内容
        val file = File(filePath)
        if (!file.exists() || !file.canRead() || !file.canWrite()) {
            println("文件不存在或无法读写")
            return
        }
        var content: String
        BufferedReader(FileReader(file)).use { reader ->
            content = reader.readLines().joinToString("\n")
        }
        // 替换字符串
        // 正则表达式匹配包含name="keyTag"的行
        val pattern: Pattern = Pattern.compile("<string name=\"${keyTag}\">.*?</string>", Pattern.DOTALL)
        val matcher: Matcher = pattern.matcher(content)
        // 替换匹配的行为空字符串，即移除该行
        val replacedContent: String = matcher.replaceAll("")
        // 按换行符分割字符串
        val lines = replacedContent.split("\n")
        // 过滤掉空行
        val nonEmptyLines = lines.filter { it.trim().isNotEmpty() }
        // 将处理后的内容合并成字符串
        val processedContent = nonEmptyLines.joinToString("\n")
        // 写入新内容到文件
        BufferedWriter(FileWriter(file)).use { writer ->
            writer.write(processedContent)
        }
        println("${keyTag}：移除成功！")
    }

    /**
     * 根据对应的多语言翻译key查询所有多语言
     */
    fun getTranslateKeyLanguages(translateKey: String, resPath: String): Map<String, String> {
        val directory = File(resPath)
        if (!directory.exists() || !directory.isDirectory) {
            println("$resPath 不存在或无法读写")
            return emptyMap()
        }
        println("translateKey：$translateKey")
        val result = mutableMapOf<String, String>()
        TRANSLATE_LIST_TAG.forEach { config ->
            val valuesName = config.valuesName // values 多语言名称
            val resAllPath = "$resPath/values-$valuesName/strings.xml"
            println("resAllPath: $resAllPath")
            println("valueName: $valuesName")
            val file = File(resAllPath)
            if (!file.exists()) {
                println("文件不存在或无法读写")
            } else {
                try {
                    val content = file.readText()
                    val regex = """<string name="$translateKey">([^<]+)</string>""".toRegex()
                    val matchResult = regex.find(content)

                    if (matchResult != null) {
                        val value = matchResult.groupValues[1]
                        println(value) // 输出匹配内容
                        config.shortName.let { shortName ->
                            result[shortName] = value
                        }
                        println("translateKey: $value")
                    } else {
                        println("未找到匹配项")
                    }
                } catch (e: IOException) {
                    println("读取文件失败: ${e.message}")
                }
            }
        }
        return result
    }


    /**
     * 解析 安卓 res 目录下的所有语种多语言
     */
    fun getLanguageList(resPath: String, findKey: String): Map<Any, Any> {
        val listLanguage = mutableMapOf<Any, Any>()

        // 遍历 listError
        for ((key, value) in TRANSLATE_LIST_TAG) {
            val valueName = value // values 多语言名称
            val resAllPath = "$resPath/values-$valueName/strings.xml" // 当前要插入的多语言的全路径
            println("resAllPath:$resAllPath")
            println("valueName:$valueName")

            val file = File(resAllPath)
            if (!file.exists()) {
                println("文件不存在或无法读写")
                continue
            }

            try {
                // 读取文件内容
                val bookshelfXml = file.readText()
                // 解析 XML 文件
                val factory = DocumentBuilderFactory.newInstance()
                val builder = factory.newDocumentBuilder()
                val inputStream = FileInputStream(file)
                val document: Document = builder.parse(inputStream)
                document.documentElement.normalize()

                val languageData = mutableMapOf<String, String>() // 当前语种对象
                val stringElements: NodeList = document.getElementsByTagName("string")
                for (i in 0 until stringElements.length) {
                    val element = stringElements.item(i) as Element
                    val keyItem = element.getAttribute("name")
                    val valueItem = element.textContent
                    languageData[keyItem] = valueItem
                }
                listLanguage[key] = languageData
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return listLanguage
    }


}